package org.thread.test04.sync.demo02;

/**
 * @author ZQX
 * @date 2025-03-12
 */
public class MyRunnable implements Runnable {
    /**
     * 电影票 - 50张
     */
    private int ticket = 50;

    // 字符串常量
    // private String lock = "";
    // private static Object lock = new Object() ;
    // private Class<?> lock = Object.class ;

    @Override
    public  void run() {
        // 要注意锁的临界区范围 - 否则别的线程没有机会进来！！
        while (true) {
            if (cell()) {
                break;
            }
        }
    }

    private synchronized boolean cell() {
        if (ticket <= 0) {
            return true;
        }

        String name = Thread.currentThread().getName();
        System.out.printf("%s 出售了第 %d 张电影票！%n", name, ticket);
        ticket--;
        return false;
    }
}
